<?php


namespace app\back\model;

use app\common\Image;
//use think\facade\Cache;
use PhpOffice\PhpSpreadsheet\Exception as ExcelException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;
use think\response\Json;
use \Exception;

class GoodsModel
{
    private static $_table = 'goods'; // 商品表
    private static $_cateTable = 'category'; // 分类表
    private static $_orgTable = 'organization'; // 组织表
    private static $_unitTable = 'goods_unit'; // 商品单位表
    private static $_logTable = 'goods_log'; // 商品操作记录表
    private static $_purchaseTable = 'purchase'; // 商品采购记录表

    /**获取添加编辑额外信息(内部调用)
     * @param $info
     * @return Json|array
     */
    protected static function getOtherStatic($info)
    {
        try {
            // 获取商品分类
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1]
            ];
            $field = 'id,name,pid,level,path';
            $cateInfo = Db::table(self::$_cateTable)->where($map)->field($field)->select()->toArray();
            if (!$cateInfo) return jsonFail('未找到可用的分类');
            // 获取分拣中心
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1]
            ];
            $field = 'id,name';
            $orgInfos = Db::table(self::$_orgTable)->where($map)->field($field)->select()->toArray();
            if (!$orgInfos) return jsonFail('未找到可用的分拣中心');
            // 商品单位
            $field = 'id,name,type';
            $unitInfo = Db::table(self::$_unitTable)->field($field)->select()->toArray();
            return ['cateInfo' => getTree($cateInfo), 'centerInfo' => $orgInfos, 'unitInfo' => $unitInfo];
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取添加编辑额外信息
     * @param $info
     * @return Json
     */
    public static function getOther($info)
    {
        $rtn = self::getOtherStatic($info);
        if (is_array($rtn)) return jsonSuccess('获取成功', $rtn);
        return $rtn;
    }

    /**添加
     * @param $input
     * @param $info
     * @return Json
     */
    public static function add($input, $info)
    {
        try {
            $input['admin_id'] = $info['id'];
            $input['description'] = '';
            $input['create_time'] = time();
            $input['cate_id'] = explode(',', $input['cate_path'])[2];
            $input['is_hot'] = $input['is_hot'] === 'true' ? 1 : 0;
            $input['is_new'] = $input['is_new'] === 'true' ? 1 : 0;
            $input['is_good'] = $input['is_good'] === 'true' ? 1 : 0;
            $input['is_activity'] = $input['is_activity'] === 'true' ? 1 : 0;
            $input['price'] = round($input['pur_price'] * $input['price_percent'] / 100, 2);
            $input['ot_price'] = round($input['pur_price'] * $input['ot_price_percent'] / 100, 2);
            $pic = Image::uploadSingle($input['image'], 'goods');
            if (!is_string($pic)) return $pic;
            $pic = $input['prefixUrl'] . '/api/uploads/' . str_replace('\\', '/', $pic);
            $input['image'] = $pic;
            $input['status'] = 1;
            unset($input['prefixUrl']);
            $id = Db::table(self::$_table)->insertGetId($input);
            if ($id) {
                return jsonSuccess('添加成功');
            }
            return jsonFail('添加失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**
     * @param $input
     * @param $info
     * @return Json
     */
    public static function list($input, $info)
    {
        try {
            $map = [
                ['g.admin_id', '=', $info['id']]
            ];
            if ($input['status'] !== '') {
                $map[] = ['g.status', '=', $input['status']];
            } else {
                $map[] = ['g.status', 'in', [1, 2]];
            }
            if ($input['cate_ids'] !== '') {
                $input['cate_ids'] = explode(',', $input['cate_ids']);
                $map[] = ['cate.path', '=', "-0-{$input['cate_ids'][0]}-{$input['cate_ids'][1]}-"];
                $map[] = ['g.cate_id', '=', $input['cate_ids'][2]];
            }
            if ($input['unit_type'] !== '') $map[] = ['u.type', '=', $input['unit_type']];
            if ($input['is_activity'] !== '') $map[] = ['g.is_activity', '=', $input['is_activity']];
            if ($input['name'] !== '') $map[] = ['g.name', 'like', "%{$input['name']}%"];
            $field = 'g.id,g.name,g.status,g.create_time,cate.name as cate_name,g.image,g.info,g.is_hot,g.is_new,g.is_good,center.name as center_name,g.pur_price,g.ot_price_percent,g.price_percent,g.ot_price,g.price,g.act_price,is_activity,g.sort,g.sales,g.stock,g.ice_stock,u.name as unit_name,u.type as unit_type';
            $table = Db::table(self::$_table)->alias('g')
                ->leftJoin([self::$_cateTable => 'cate'], 'cate.id = g.cate_id')
                ->leftJoin([self::$_orgTable => 'center'], 'center.id = g.center_id')
                ->leftJoin([self::$_unitTable => 'u'], 'u.id = g.unit_id')
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取搜索分类（1到3级）列表
     * @param $info
     * @return Json
     */
    public static function getCategorySimpleList($info)
    {
        try {
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1],
                ['level', '<=', 2]
            ];
            $rtn = Db::table(self::$_cateTable)->field('id,pid,name')->where($map)->select()->toArray();
            if (!$rtn) return jsonFail('没有可用的分类');
            return jsonSuccess('获取成功', getTree($rtn));
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改状态
     * @param $input
     * @param $info
     * @return Json
     */
    public static function changeStatus($input, $info)
    {
//        $flag = false;
        try {
            $id = $input['id'];
            unset($input['id']);
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('admin_id,status')->where('id', $id)->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            $map = [
                ['id', '=', $id],
                ['admin_id', '=', $info['id']],
                ['status', '=', $input['status'] == 1 ? 2 : 1]
            ];
//            Db::startTrans();
//            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update(['status' => $input['status']]);
            if ($rtn) {
                // 修改缓存
//                $redisRtn = Cache::store('redis')->handler()->hMset('sxb-goods-' . $id, $input);
//                if ($redisRtn === true) {
//                    Db::commit();
                return jsonSuccess('状态修改成功');
//                }
            }
//            Db::rollback();
            return jsonFail('数据没有更新，请刷新页面重试，状态修改失败');
        } catch (Exception $e) {
//            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**修改商品热卖|新品|优品推荐状态
     * @param $input
     * @param $info
     * @return Json
     */
    public static function changeIsStatus($input, $info)
    {
//        $flag = false;
        try {
            $id = $input['id'];
            unset($input['id']);
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('admin_id')->where('id', $id)->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            $map = [
                ['id', '=', $id],
                ['admin_id', '=', $info['id']],
                [$input['is_name'], '=', $input['is_status'] == 1 ? 0 : 1]
            ];
//            Db::startTrans();
//            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update([$input['is_name'] => $input['is_status']]);
            if ($rtn) {
                // 修改缓存
//                $data = [
//                    $input['is_name'] => $input['is_status']
//                ];
//                $redisRtn = Cache::store('redis')->handler()->hMset('sxb-goods-' . $id, $data);
//                if ($redisRtn === true) {
//                    Db::commit();
                return jsonSuccess('状态修改成功');
//                }
            }
//            Db::rollback();
            return jsonFail('数据没有更新，请刷新页面重试，状态修改失败');
        } catch (Exception $e) {
//            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**删除（软删除）
     * @param $input
     * @param $info
     * @return Json
     */
    public static function del($input, $info)
    {
//        $flag = false;
        try {
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('admin_id,status')->where('id', $input['id'])->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['status', 'in', [1, 2]]
            ];
//            Db::startTrans();
//            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update(['status' => 3]);
            if ($rtn) {
//                $redisRtn = Cache::store('redis')->handler()->hMset('sxb-goods-' . $input['id'], ['status' => 3]);
//                if ($redisRtn === true) {
//                    Db::commit();
                return jsonSuccess('删除成功');
//                }
            }
//            Db::rollback();
            return jsonFail('操作失败,请点击刷新按钮重新查看');
        } catch (Exception $e) {
//            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个信息
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getOnly($input, $info)
    {
        try {
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('id,admin_id,name,cate_path,center_id,image,info,ot_price_percent,price_percent,pur_price,act_price,sort,status,unit_id')->where('id', $input['id'])->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            unset($goods['admin_id']);
            unset($goods['status']);
            $rtn = self::getOtherStatic($info);
            if (!is_array($rtn)) return $rtn;
            return jsonSuccess('获取成功', array_merge(['info' => $goods], $rtn));
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑信息
     * @param $input
     * @param $info
     * @param $prefixUrl
     * @return Json
     */
    public static function edit($input, $info, $prefixUrl)
    {
        try {
            // 获取当前信息
            $id = $input['id'];
            $input['cate_id'] = explode(',', $input['cate_path'])[2];
            unset($input['id']);
            $goods = Db::table(self::$_table)->field('admin_id,status,image')->where('id', $id)->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            $input['price'] = round($input['pur_price'] * $input['price_percent'] / 100, 2);
            $input['ot_price'] = round($input['pur_price'] * $input['ot_price_percent'] / 100, 2);
            if ($input['image']) {
                $pic = Image::uploadSingle($input['image'], 'goods');
                if (!is_string($pic)) return $pic;
                $input['image'] = $prefixUrl . '/api/uploads/' . str_replace('\\', '/', $pic);
                $rtn = Db::table(self::$_table)->where('id', $id)->update($input);
                if ($rtn) {
                    $filePath = explode('/', $goods['image']);
                    unset($filePath[0]);
                    unset($filePath[1]);
                    unset($filePath[2]);
                    unset($filePath[3]);
                    Image::delete(app()->getRootPath() . '/' . implode('/', $filePath));
                    return jsonSuccess('编辑成功');
                }
                return jsonFail('编辑失败');
            } else {
                unset($input['image']);
                $rtn = Db::table(self::$_table)->where('id', $id)->update($input);
                if ($rtn) {
                    return jsonSuccess('编辑成功');
                }
                return jsonFail('编辑失败');
            }
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取详情
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getDesc($input, $info)
    {
        try {
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('id,admin_id,status,description')->where('id', $input['id'])->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            unset($goods['admin_id']);
            unset($goods['status']);
            return jsonSuccess('获取成功', $goods);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑详情
     * @param $input
     * @param $info
     * @return Json
     */
    public static function editDesc($input, $info)
    {
        try {
            // 获取当前信息
            $goods = Db::table(self::$_table)->field('id,admin_id,status,description')->where('id', $input['id'])->find();
            if (!$goods) return jsonFail('未找到商品信息');
            if ($goods['admin_id'] != $info['id']) return jsonFail('该商品非您直接管理，您没有权限操作');
            if ($goods['status'] == 3) return jsonFail('该商品已删除无法继续操作');
            //获取原先文本当中的图片
            preg_match_all('/(http.*\.(jpg|jpeg|gif|png))/U', $goods['description'], $oldMatches);
            preg_match_all('/(http.*\.(jpg|jpeg|gif|png))/U', $input['description'], $newMatches);
            $diffArr = array_diff($oldMatches[1], $newMatches[1]);
            $deleteData = [];
            foreach ($diffArr as $v) {
                $filePath = explode('/', $v);
                unset($filePath[0]);
                unset($filePath[1]);
                unset($filePath[2]);
                unset($filePath[3]);
                $deleteData[] = app()->getRootPath() . implode('/', $filePath);
//
            }
//            var_dump($input['description']);
            Image::delete($deleteData);
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['status', 'in', '1,2']
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['description' => $input['description']]);
            if ($rtn) return jsonSuccess('编辑成功');
            return jsonFail('编辑失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**查看出库入库报损记录
     * @param $input
     * @return Json
     */
    public static function getLogList($input)
    {
        try {
            $map = [
                ['l.goods_id', '=', $input['goods_id']]
            ];
            if ($input['type'] == 4) {
                // 获取采购信息
                $field = 'l.id,o.name as center_name,l.price,l.p_weight,l.w_weight,l.reason,l.name,l.phone,l.role_type,l.status,l.type,l.create_time';
                $table = Db::table(self::$_purchaseTable)->alias('l')
                    ->leftJoin([self::$_orgTable => 'o'], 'o.id = l.center_id');
            } else {
                // 入库 出库  报损
                $field = 'l.id,l.equipment,l.order_id,l.weight,l.reason,l.phone,l.role_type,l.name,l.create_time';
                $table = Db::table(self::$_logTable)->alias('l');
                $map[] = ['l.type', '=', $input['type']];
            }
            $table = $table->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => [], 'log_type' => $input['type']]);
            $list = $table->page($input['page'], $input['limit'])->order('l.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list, 'log_type' => $input['type']]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取商品入库记录列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function goodsInList($input, $info)
    {
        try {
            $map = [
                ['gl.admin_id', '=', $info['id']],
                ['gl.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]],
                ['gl.type', '=', 1]
            ];
            $table = Db::table(self::$_logTable)->alias('gl')
                ->join([self::$_table => 'g'], 'g.id = gl.goods_id')
                ->join([self::$_orgTable =>'c'], 'c.id = g.center_id')
                ->join([self::$_unitTable => 'gu'], 'gu.id = g.unit_id')
                ->where($map);
            if ($input['name'] != '') {
                $option = [
                    ['admin_id', '=', $info['id']],
                    ['name', 'like', "%{$input['name']}%"]
                ];
                $buildSql = Db::table(self::$_orgTable)->field('id')->where($option)->buildSql();
                $table->join([$buildSql => 'b'], '1')->whereRaw('find_in_set(c.id, b.id)');
            }
            $table->group('g.id');
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->removeOption('field')
                ->field('c.name as center_name,sum(gl.weight) as total_weight,g.id,g.name,gu.name as unit_name')
                ->page($input['page'], $input['limit'])
                ->order('gl.create_time', 'desc')
                ->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**导出商品入库记录excel
     * @param $input
     * @param $info
     * @return Json
     */
    public static function goodsInExcel($input, $info)
    {
        try {
            $map = [
                ['gl.admin_id', '=', $info['id']],
                ['gl.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]],
                ['gl.type', '=', 1]
            ];
            $table = Db::table(self::$_logTable)->alias('gl')
                ->join([self::$_table => 'g'], 'g.id = gl.goods_id')
                ->join([self::$_orgTable =>'c'], 'c.id = g.center_id')
                ->join([self::$_unitTable => 'gu'], 'gu.id = g.unit_id')
                ->where($map);
            if ($input['name'] != '') {
                $option = [
                    ['admin_id', '=', $info['id']],
                    ['name', 'like', "%{$input['name']}%"]
                ];
                $buildSql = Db::table(self::$_orgTable)->field('id')->where($option)->buildSql();
                $table->join([$buildSql => 'b'], '1')->whereRaw('find_in_set(c.id, b.id)');
            }
            $table->group('g.id');
            $data = $table->field('g.id,g.name,c.name as center_name,sum(gl.weight) as total_weight,gu.name as unit_name')
                ->order('gl.create_time', 'desc')->select()->toArray();
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            //设置工作表标题名称
            $sheet->setTitle('sheet1');
            $sheet->setCellValue('A1', '商品ID');
            $sheet->setCellValue('B1', '商品名称');
            $sheet->setCellValue('C1', '分拣中心名称');
            $sheet->setCellValue('D1', '数量');
            $sheet->setCellValue('E1', '单位');
            $sheet->fromArray(
                $data,
                null,
                'A2'
            );

//            $spreadsheet->setActiveSheetIndex(0);
            $writer = new Xlsx($spreadsheet);
            ob_start(); //打开缓冲区
            $writer->save('php://output');
            $xlsData = ob_get_contents();
            ob_end_clean(); // 清除缓冲
            return jsonSuccess('excl生成成功，进行下载...', "data:application/vnd.ms-excel;base64," . base64_encode($xlsData));
        } catch (ExcelException $e) {
            return jsonFail($e->getMessage());
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}